<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <el-button icon="el-icon-circle-check" type="primary" plain @click.stop="changeSelect()">{{ activeName === "1"
              ? "收起筛选" : "展开筛选" }}</el-button>
          </template>
          <SearchForm :formItems="formItems" @getSearchData="getSearchData" @SelectChange="SelectChange"></SearchForm>
        </el-collapse-item>
      </el-collapse>
      <ActionBar :export-active="true" :hasExport="true" :hasAdd="false" :hasDel="false" :page-no="162" @add="add"
        @del="del" @exportFile="exportFile" />
    </template>

    <template v-slot:btnsBar>
      <OperationBar :categoryList="operationList" @categoryBar="operationEunm" />
    </template>

    <!-- <template v-slot:categoryBox>
      <CategoryBar :categoryList="auditList" @categoryBar="auditEunm" v-show="routerPath !== '/history-query-sr'" />
    </template> -->

    <template v-slot:content>
      <Table :propList="propList" :listData="tableData">
        <!-- 批次编号 -->
        <template v-slot:batchName="{ row }">
          <div v-show="row.pondName">
            {{ row.batchName ? row.batchName : '--' }}
          </div>
        </template>
        <!-- 物料 -->
        <template v-slot:materialUnit="{ row }">
          <div v-if="row.materialId && materialObj[row.materialId]">
            {{ row.num }}{{ materialObj[row.materialId]['unit'] || '' }}
          </div>
        </template>
        <!-- 物料数量 -->
        <template v-slot:quantityInput="{ row }">
          <div v-if="row.materialId && materialObj[row.materialId]">
            {{ (row.num / materialObj[row.materialId]['ratioNum']).toFixed(2) }}{{ materialObj[row.materialId]['aUnit'] }}
          </div>
        </template>
        <!-- 规格-->
        <template v-slot:spec="{ row }">
          <div v-if="row.materialId && materialObj[row.materialId]">
            {{ materialObj[row.materialId]['ratio'] || '' }}
          </div>
        </template>
        <template v-slot:footer>
          <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
            @changeCurrentPage="changeCurrentPage" />
        </template>
      </Table>
      <!-- <AddEditDialog :isPassType="isPassType" :dialogParams="dialogParams" :show="showDialog"
        @cancelDialog="cancelPassDialog" @submitAudite="submitAudite" /> -->
      <ExportBtn ref="ExportBtn" :btnName="'作业报表'" :apiName="currentExport" :searchObj="searchObj"></ExportBtn>
    </template>

  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";              // 分页
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import Table from "@/components/table/index.vue";              // 数据表
import SearchForm from "@/components/SearchForm/index.vue";
import CategoryBar from "./components/CategoryBar";            // 分类栏
import OperationBar from "./components/CategoryBar.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import ExportBtn from "@/components/ExportBtn";


import EnumApi from "@/api/enum"; //审核枚举
import BreedingTypeManageApi from "@/api/basic-info-manage/breeding-type-manage/index";//养殖方式内聚
import FeedingOperationApi from "@/api/operation-management/feeding-operation"; //投喂
import HangingOperationApi from "@/api/operation-management/hanging-operation"; //吊网
import DewNetOperationApi from "@/api/operation-management/dew-net-operation"; //漏网

import BatchMangeApi from "@/api/batch-mange";
import MaterialApi from "@/api/basic-info-manage/material";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import StaffApi from "@/api/basic-info-manage/staff";
import store from "@/store";

import { mymixin } from "@/utils/mixin";
export default {
  name: "WaterChangeOperation",
  components: {
    CategoryBar,
    ActionBar,
    Pagination,
    Table,
    SearchForm,
    BaseMainSlot,
    AddEditDialog,
    OperationBar,
    ExportBtn
  },
  mixins: [mymixin],
  data() {
    return {
      routerPath: '',  // 当前路由
      variousOperation: "吊网作业",//当前作业类型
      currentExport: '',   //当前导出接口
      searchObj: {},
      searchParams: {
        staffName: "", //作业人
        batchName: "", //批次编号
        fishPondId: "", //鱼塘ID
        workBeginTime: "", //作业开始时间
      },

      batchList: [], //批次列表
      materialList: [], //物料列表
      fishPondList: [], //鱼塘列表
      staffList: [], //作业人列表

      activeName: "",
      dialogParams: {},
      showDialog: false,
      isPassType: "",
      auditedIdName: "",
      auditType: "PASS", //默认待审核   审核：REVIEW
      eunmApi: HangingOperationApi, //默认 吊网接口
      pageSize: 10,
      currentPage: 1,
      totalSize: 10,
      auditIndex: 0,
      operationIndex: 0,
      auditList: [],

      formItems: [],
      propList: [],   // 数据表格
      tableData: [],
      operationList: [
        {
          id: 0,
          value: "吊网作业",
          api: HangingOperationApi,
          auditedIdName: "hangNetWorkId",
          propList: [
            { prop: "pondName", label: "鱼塘名称", minWidth: "80" },
            // { prop: "batchName", label: "批次编号", minWidth: "80" },
            { label: "批次编号", minWidth: "80", slotName: "batchName" },
            { prop: "position", label: "位置", minWidth: "80" },
            { prop: "season", label: "季节", minWidth: "80" },
            { prop: "staffName", label: "作业人", minWidth: "80" },
            { prop: "workBeginTime", label: "作业开始时间", minWidth: "80" },
          ],
          formItems: [
            {
              defaultValue: "",
              field: "fishPondId",
              type: "Select",
              label: "鱼塘名称:",
              placeholder: "请选择鱼塘名称",
              options: [],
              optionProps: { value: "fishPondId", label: "pondName" },
            },
            {
              defaultValue: "",
              field: "productionBatchId",
              type: "Select",
              label: "批次编号:",
              placeholder: "请选择批次编号",
              options: [],
              optionProps: { value: "productionBatchId", label: "mnecode" },
            },
            {
              defaultValue: "",
              field: "staffName",
              type: "Select",
              label: "作业人:",
              placeholder: "请选择作业人",
              options: [],
              optionProps: { value: "staffName", label: "staffName" },
            },
            {
              defaultValue: "",
              field: "workDateTime",
              type: "DatePicker",
              label: "作业日期:",
              placeholder: "请选择作业日期",
            },
          ],
        },
        {
          id: 1,
          value: "露网作业",
          api: DewNetOperationApi,
          auditedIdName: "exposedNetWorkId",
          propList: [
            { prop: "pondName", label: "鱼塘名称", minWidth: "80" },
            // { prop: "batchName", label: "批次编号", minWidth: "80" },
            { label: "批次编号", minWidth: "80", slotName: "batchName" },
            { prop: "position", label: "位置", minWidth: "80" },
            { prop: "season", label: "季节", minWidth: "80" },
            { prop: "staffName", label: "作业人", minWidth: "80" },
            { prop: "workBeginTime", label: "作业开始时间", minWidth: "80" },
          ],
          formItems: [
            {
              defaultValue: "",
              field: "fishPondId",
              type: "Select",
              label: "鱼塘名称:",
              placeholder: "请选择鱼塘名称",
              options: [],
              optionProps: { value: "fishPondId", label: "pondName" },
            },
            {
              defaultValue: "",
              field: "productionBatchId",
              type: "Select",
              label: "批次编号:",
              placeholder: "请选择批次编号",
              options: [],
              optionProps: { value: "productionBatchId", label: "mnecode" },
            },
            {
              defaultValue: "",
              field: "staffName",
              type: "Select",
              label: "作业人:",
              placeholder: "请选择作业人",
              options: [],
              optionProps: { value: "staffName", label: "staffName" },
            },
            {
              defaultValue: "",
              field: "workDateTime",
              type: "DatePicker",
              label: "作业日期:",
              placeholder: "请选择作业日期",
            },
          ],
        },
        {
          id: 2,
          value: "投喂作业",
          api: FeedingOperationApi,
          auditedIdName: "feedingWorkId",
          propList: [
            { prop: "pondName", label: "鱼塘名称", minWidth: "80" },
            { label: "批次编号", minWidth: "80", slotName: "batchName" },
            { prop: "materialName", label: "物料名称", minWidth: "80" },
            { slotName: "materialUnit", label: "物料量" },
            { slotName: "quantityInput", label: "投入数量" },
            { slotName: "spec", label: "物料规格", minWidth: "50" },
            { prop: "workDateTime", label: "作业时间", minWidth: "80" },
          ],
          formItems: [
            {
              defaultValue: "",
              field: "fishPondId",
              type: "Select",
              label: "鱼塘名称:",
              placeholder: "请选择鱼塘名称",
              options: [],
              optionProps: { value: "fishPondId", label: "pondName" },
            },
            {
              defaultValue: "",
              field: "productionBatchId",
              type: "Select",
              label: "批次编号:",
              placeholder: "请选择批次编号",
              options: [],
              optionProps: { value: "productionBatchId", label: "mnecode" },
            },
            {
              defaultValue: "",
              field: "materialId",
              type: "Select",
              label: "物料名称:",
              placeholder: "请选择物料名称",
              options: [],
              optionProps: { value: "materialId", label: "name" },
            },
            {
              defaultValue: "",
              field: "staffName",
              type: "Select",
              label: "作业人:",
              placeholder: "请选择作业人",
              options: [],
              optionProps: { value: "staffName", label: "staffName" },
            },
            {
              defaultValue: "",
              field: "workDateTime",
              type: "DatePicker",
              label: "作业日期:",
              placeholder: "请选择作业日期",
            },
          ],
        },
      ],
      moduleValue: {}
    };
  },

  computed: {
    materialObj() {
      return store.state.basicData.material;
    }
  },
  created() {
    this.routerPath = this.$route.path
  },
  mounted() {
    this.initData();
    this.$bus.$on("currentOperation", (v) => {
      this.variousOperation = v
    })
  },
  watch: {
    variousOperation: {
      handler(newV) {
        if (newV === "吊网作业") {
          this.currentExport = 'exportHangNetWork'
        }
        if (newV === "露网作业") {
          this.currentExport = 'exportExposedNetWork'
        }
        if (newV === "投喂作业") {
          this.currentExport = 'exportFeedingWork'
        }
      }, immediate: true
    }
  },
  methods: {
    SelectChange(value) {
      if (this.moduleValue.fishPondId !== value.fishPondId) {
        this.$set(this, 'moduleValue', JSON.parse(JSON.stringify(value)))
        value.productionBatchId = ''
      }
      this.formItems.forEach((item) => {
        switch (item.field) {
          case "fishPondId":
            item.defaultValue = value.fishPondId
            item.options = this.fishPondList ? this.fishPondList : [];
            break;
          case "productionBatchId":
            // debugger
            item.defaultValue = value.productionBatchId
            item.options = this.batchList ? this.batchList.filter((item) => {
              return item.fishPondId == value.fishPondId || !value.fishPondId
            }) : [];
            break;
          case "staffName":
            item.defaultValue = value.staffName
            item.options = this.staffList ? this.staffList : [];
            break;
          case "materialId":
            item.defaultValue = value.materialId
            item.options = this.materialList ? this.materialList : [];
            break;
          default:
            item.options = [];
        }
      });
    },
    //查询
    getSearchData(data) {
      console.log("筛选数据", this.delObjEmptyType(data));
      this.searchParams = this.delObjEmptyType(data);
      this.currentPage = 1;
      this.queryPageList();
    },
    //初始化
    initData() {
      this.propList = this.operationList[0].propList;
      this.auditedIdName = this.operationList[0].auditedIdName;
      this.formItems = JSON.parse(
        JSON.stringify(this.operationList[0].formItems)
      );
      this.querySelectedList();
      this.queryEnumList();
      this.queryPageList();
    },
    //作业eunm
    operationEunm(data) {
      this.currentPage = 1;
      this.eunmApi = data.api;
      this.propList = data.propList ? data.propList : [];
      this.formItems = data.formItems
        ? JSON.parse(JSON.stringify(data.formItems))
        : [];
      this.auditedIdName = data.auditedIdName;
      this.searchParams = {};
      this.queryPageList();
      this.getOptions();
      // this.isAddSolt();
    },

    // 获取下拉
    getOptions() {
      console.log(this.formItems, "formItems");
      this.formItems.forEach((item) => {
        switch (item.field) {
          case "fishPondId":
            item.options = this.fishPondList ? this.fishPondList : [];
            break;
          case "productionBatchId":
            item.options = this.batchList ? this.batchList : [];
            break;
          case "staffName":
            item.options = this.staffList ? this.staffList : [];
            break;
          case "materialId":
            item.options = this.materialList ? this.materialList : [];
            break;
          default:
            item.options = [];
        }
      });
      console.log(this.formItems);
    },
    //是否添加操作
    // isAddSolt() {
    //   let index = this.propList.findIndex((value) => {
    //     return value.slotName == "operation";
    //   });
    //   if (this.auditType == "PASS") {
    //     index != -1 && this.propList.splice(index, 1);
    //   } else {
    //     index == -1 &&
    //       this.propList.push({
    //         label: "操作",
    //         slotName: "operation",
    //       });
    //   }
    // },
    //审核eunm
    // auditEunm(data) {
    //   console.log("auditType", data.name);
    //   this.currentPage = 1;
    //   this.auditType = data.name;
    //   this.queryPageList();
    // },
    //获取枚举
    queryEnumList() {
      this.auditList = [];
      EnumApi.list({ enumType: "AuditType" }).then((res) => {
        if (res.data) {
          res.data.forEach((item, index) => {
            this.auditList.push({
              id: index,
              name: item.name,
              value: item.value,
            });
          });
        }
      });
    },
    //获取查询条件的下拉列表
    querySelectedList() {
      Promise.all([
        BatchMangeApi.queryByCondition({}), //可选批次
        MaterialApi.queryByCondition(), //可选物料
        FishPondApi.queryByCondition(), //可选鱼塘
        StaffApi.queryByCondition(), //作业人
      ])
        .then((results) => {
          console.log("success:", results);
          this.batchList = results[0] ? results[0].data : [];
          this.materialList = results[1] ? results[1].data : [];
          this.fishPondList = results[2] ? results[2].data : [];
          this.staffList = results[3] ? results[3].data : [];
          this.getOptions();
        })
        .catch((e) => {
          console.log("error", e);
        });
    },

    //获取表单
    queryPageList() {
      let searchData = this.delObjEmptyType(this.searchParams);
      let params = {
        page: this.currentPage,
        size: this.size,
        entity: { auditType: this.auditType, ...searchData },
      };
      if (this.routerPath == '/history-query-sr') {
        params.entity.auditType = 'PASS';
      } else {
        params.entity.auditType = this.auditType;
      }
      this.searchObj = JSON.parse(JSON.stringify(params.entity))
      this.eunmApi.queryPageByCondition(params).then((res) => {
        if (res.success === true) {
          this.tableData = res.data.content;
          this.totalSize = res.data.totalElements;
          this.addblankmet();
          this.resetActionBar();
          console.log(this.totalSize);
        }
      });
    },
    //显示弹窗
    cancelPassDialog() {
      this.showDialog = false;
    },
    showAuditDialog(row, type) {
      this.auditedId = row["auditedIdName"];
      this.isPassType = type;
      this.dialogParams = row;
      this.showDialog = true;
    },
    submitAudite(data) {
      let params = {};
      if (this.nowChanceStau === "pass") {
        params = {
          // 审核
          auditedId: this.auditedId,
          auditStaffId: sessionStorage.getItem("staffId"),
          auditStaffName: sessionStorage.getItem("staffName"),
          auditType: "PASS",
        };
      } else if (this.nowChanceStau === "unpass") {
        params = {
          auditedId: this.auditedId,
          auditStaffId: sessionStorage.getItem("staffId"),
          auditStaffName: sessionStorage.getItem("staffName"),
          auditType: "NOT_PASS",
          failReason: data.failReason,
        };
      }
      HangingOperationApi.audit(params).then((res) => {
        if (res.success) {
          this.$message.success("操作通过");
          this.queryPageList();
        } else {
          this.$message.info(res.message ? res.message : "系统错误,请稍后再试");
        }
        this.showDialog = false;
      });
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      console.log(currentPage);
      this.queryPageList();
    },
    //去除对象空属性
    delObjEmptyType(obj) {
      for (let key in obj) {
        if (!obj[key]) {
          delete obj[key];
        }
      }
      return obj;
    },
  },
};
</script>

<style lang="scss" scoped></style>
